<?php
namespace app\common\lib\module_config\tagsconfig;

use app\common\lib\model_operate\Tools;
use app\common\lib\module_config\FormCtrl;
use app\common\lib\module_config\TagsConfig;
use think\Db;

class Add extends TagsConfig
{

    private $base; //主表信息

    /**
     * 构造
     */
    public function __construct($trace, $tags)
    {
        parent::__construct($trace, $tags);
        //设置主表信息
        $this->setBase();
    }

    /**
     * 设置主表信息
     */
    private function setBase()
    {
        //主表名
        $this->base['tableName'] = Tools::tableNameFormat($this->trace->getApp(), 1);
        //获取主表字段
        $this->base['tableInfo']     = DB::getTableInfo($this->base['tableName']);
        $this->base['displayFields'] = [];
    }

    /**
     * 获取主表信息
     */
    public function getBase()
    {
        return $this->base;
    }

    public function createQuery()
    {
        return '子类 Add 实现的获取数据方法';
    }

    /**
     * 创建分离引入html的html
     */
    public function createArrayhtml()
    {
        //实例化控件生成类
        $fo = new FormCtrl($this->trace, $this->tags);

        $html = '';

        if (empty($this->config['fields'])) {
            return '';
        }
        $da = [];
        $i  = 0;
        //非引入html控件
        //引入和非引入拆成数组
        foreach ($this->config['fields'] as $key => $value) {

            //判断是否是引入html
            if ($value['ctrl_type'] == 'htmlpage' && $value['is_show'] == 1 && !empty($value['html'])) {
                if (empty($da[$i])) {
                    $da[$i] = $fo->setHtmlpage($value);
                    $i++;
                } else {
                    $i++;
                    $da[$i] = $fo->setHtmlpage($value);
                }
                continue;
            }
            //show_type 1.查表 2.固定内容 3.多选项
            if ($value['show_type'] == 1) {
                $value['option'] = $this->selectGetTableData($value['option']);
            } elseif ($value['show_type'] == 2) {
                $value['option'] = json_decode($value['option'], true);
            } elseif ($value['show_type'] == 3) {
                $value['option'] = json_decode($value['option'], true);
            }
            //add中如果隐藏，避免添加时报错，生成一个隐藏input
            if ($value['is_show'] == 1) {
                $html .= $fo->setHtml($value);
            } else {
                //设置主键
                if ($value['field'] == $this->getPk()) {
                    // $html .= $fo->setHidden($value);
                } else {
                    $html .= $fo->setHidden($value);
                }
            }

            if (empty($da[$i])) {
                $da[$i] = $html;

            } else {
                $da[$i] = $html;
                // $da[$i] = $da[$i].$html;
            }

        }

        // return $html;
        return $da;
    }

    /**
     * 创建html
     */
    public function createHtml()
    {
        //实例化控件生成类
        $fo = new FormCtrl($this->trace, $this->tags);

        $html = '';

        if (empty($this->config['fields'])) {
            return '';
        }

        foreach ($this->config['fields'] as $key => $value) {
            //show_type 1.查表 2.固定内容 3.多选项
            if ($value['show_type'] == 1) {
                $value['option'] = $this->selectGetTableData($value['option']);
            } elseif ($value['show_type'] == 2) {
                $value['option'] = json_decode($value['option'], true);
            } elseif ($value['show_type'] == 3) {
                $value['option'] = json_decode($value['option'], true);
            }
            //add中如果隐藏，避免添加时报错，生成一个隐藏input
            if ($value['is_show'] == 1) {
                $html .= $fo->setHtml($value);
            } else {
                //设置主键
                if ($value['field'] == $this->getPk()) {
                    // $html .= $fo->setHidden($value);
                } else {
                    $html .= $fo->setHidden($value);
                }
            }
        }

        // //获取html
        // $h = new \plugins\goods\interfaceLib\GoodsSpecClassify();

        // $c = $h->pidGetSpec('abc','1');

        // dump($c);

        // $html.= $c;

        return $html;
    }

    /**
     * 查表显示数据
     */
    private function selectGetTableData($option)
    {
        $da     = [];
        $option = json_decode($option, true);
        if (!empty($option) && count($option) == 3) {
            list($table, $fields, $items) = $option;
            $table                        = Tools::tableNameFormat($table);
            $tb                           = Db::name($table)->field($fields)->select()->toArray();
            foreach ($items as $key => $value) {
                if (false === strpos($key, '$') && false === strpos($value, '$')) {
                    $da[$key] = $value;
                } else {
                    $ik = str_replace("$", '', $key);
                    $iv = str_replace("$", '', $value);
                    $a  = array_column($tb, $iv, $ik);
                    $da = $da + $a;
                }
            }
        }
        return $da;
    }

    /**
     * 获取主键
     */
    public function getPk()
    {
        $pk = $this->base['tableInfo']['pk'];

        return $pk;
    }

    /**
     * 执行添加
     */
    public function saveAdd($param)
    {
        //获取模块名
        $module_name = $this->trace->getApp();
        //调用主表模型类
        $str = 'plugins\\' . $module_name . '\\model\\' . cmf_parse_name($module_name, 1) . 'Model';

        $model = new $str();
        //根据控件处理数据
        $rs = $this->transform($param, $model);

        if ($rs['status'] !== true) {
            return $rs;
        }

        // try {
        //执行添加
        $result = $model->allowField(true)->save($param);

        $res = $this->saveRelevancePage($model, $param);

        $pk     = $this->getPk();
        $result = $model->$pk; //添加成功返回主键值

        return ['status' => true, 'message' => '添加成功', 'code' => 200, 'data' => $result];
        // } catch (\Exception $e) {
        //     return ['status' => false, 'message' => '添加失败', 'code' => 106];
        // }
    }

    /**
     * 获取模块中html.json文件
     */
    public function getHtmlConfig()
    {
        $module_name = $this->trace->getApp();

        $res = getModuleConfig($module_name, 'config', 'html.json');

        $res = json_decode($res, true);

        if (!empty($res['html'])) {

            return $res['html'];
        }

        return $res;
    }

    /**
     * 保存关联页面
     */
    public function saveRelevancePage(&$model, &$param)
    {
        //获取配置信息
        $config = $this->config['fields'];
        //获取tag
        $tag = $this->tags;

        //获取引入的
        $html_configs = $this->getHtmlConfig();

        $search = 'htmlpage';
        foreach ($config as $key => $value) {
            if ($value['ctrl_type'] != 'htmlpage') {
                continue;
            }

            $search = $value['html'];

            $html_config = array_filter($html_configs, function ($t) use ($search) {return $t['name'] == $search;});

            //执行添加
            if (empty($html_config)) {
                continue;
            }

            $html_config = array_values($html_config)[0];

            if (empty($html_config[$tag]['save'])) {
                continue;
            }

            $save = $html_config[$tag]['save'];

            if (empty($save['controller'])) {
                continue;
            }

            $cto   = explode('@', $save['controller']);
            $class = $cto[0];
            $func  = $cto[1];

            //判断类是否定义
            if (!class_exists($class)) {
                return $class . '类未定义,不能生辰html';
            }

            $class = '\\' . $class;

            $cls = new $class();

            //判断类方法是否定义
            if (!method_exists($class, $func)) {
                return $class . '类中' . $func . '方法未定义';
            }

            //获取要传的字段
            if (!empty($save['field'])) {
                $fd    = $save['field'];
                $field = $model->$fd;
            } else {
                $field = '';
            }

            $pa = $param[$value['field']];

            //第一个字段传数据
            $html = $cls->$func($pa, $field);

            return $html;
        }
    }

    /**
     * 保存添加时数据处理
     */
    public function transform(&$param, &$model)
    {

        $config = $this->config['fields'];

        unset($param['_plugin'], $param['_controller'], $param['_action']);

        foreach ($param as $key => $value) {

            if (empty($config[$key])) {
                continue;
            }

            //判断唯一字段
            if ($config[$key]['is_sole'] == 1) {
                $res = $model->get([$key => $value]);
                if (!empty($res)) {
                    return ['status' => false, 'message' => $config[$key]['title'] . '已存在', 'code' => 105];
                }
            }

            switch ($config[$key]['ctrl_type']) {
                case 'date':
                    $param[$key] = strtotime($param[$key]);
                    break;
                case 'checkbox':
                    $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                    break;
                case 'moreimage':
                    $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                    break;
                case 'htmlpage':

                    $rs = $this->yrhtmlisNull($config[$key]['html']);
                    //如果为空
                    if ($rs == true) {
                        //如果不是字符串
                        if (!is_string($param[$key])) {
                            $param[$key] = json_encode($param[$key], JSON_UNESCAPED_UNICODE);
                        }
                    }
                    break;
                default:
                    # code...
                    break;
            }
        }

        return ['status' => true, 'message' => 'success', 'code' => 200];
    }

    /**
     * 引入html中的save的controller 是否为空
     */
    public function yrhtmlisNull($ht)
    {
        if (empty($ht)) {
            return true;
        }

        $config = $this->config['fields'];

        $html_configs = $this->getHtmlConfig();

        //获取tag
        $tag = $this->tags;

        $html_config = array_filter($html_configs, function ($t) use ($ht) {return $t['name'] == $ht;});

        $html_config = array_values($html_config)[0];

        if (empty($html_config[$tag]['save']['controller'])) {
            return true;
        }

        return false;
    }

    /**
     * 设置参数
     */
    public function setParam()
    {
        return true;
    }

}
